<?php


namespace backend\controllers;


use common\cache\DictCache;
use common\components\OrderBehavior;
use common\helpers\commonApi;
use common\helpers\TransformApi;
use common\models\BusinessReview;
use common\models\GoodsComment;
use common\models\Order;
use common\models\OrderComment;
use common\models\OrderGoods;
use common\models\OrderLog;
use common\models\OrderRefund;
use common\models\RedEnvelopes;
use common\models\Set;
use common\models\System;
use common\models\User;
use common\services\ConfigService;
use common\services\MenuService;
use Da\QrCode\QrCode;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 订单控制器
 * Class OrderController
 * @package backend\controllers
 */
class OrderController extends BaseController
{
    public function init()
    {
        parent::init();
        $this->model = Order::className();
    }

    /**
     * 列表
     * @return array|string
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isPost) {
            $where = [];
            $return = parent::actionIndex(true, $where, ['create_time' => 'desc'], ['goods']);
            $list = $return['data'];
            //支付状态
            $pay_status = DictCache::get('sys_order_pay_status');
            //订单状态
            $order_status = DictCache::get('sys_order_order_status');
            //用户信息
            $userids = array_unique(ArrayHelper::getColumn($list, 'userid'));
            $user = User::find()->where(['id'=>$userids])->select(['id','info'])->asArray()->all();
            $userInfo = (new User())->getUserHtml($user);
            foreach ($list as $key => $val) {
                $val['pay_status_name'] = $pay_status[$val['pay_status']] ?? '';
                $val['order_status_name'] = $order_status[$val['order_status']] ?? '';
                $val['pay_time'] = $val['pay_time'] ?? '';
                $val['good_html'] = "<div id='main_picture_{$val['id']}'>";
                foreach ($val['goods'] as $good) {
                    $val['good_html'] .= '<div class="row" style="text-align: left;">';
                    $good_info = json_decode($good['good_info'], true);
                    $img = $good_info['main_img'];
                    $name = $good['good_name'];
                    $s_name = mb_substr($name, 0, 6);
                    $val['good_html'] .= "<div class='col-md-4'><img  style='width: 80px;' src='$img' alt=''></div>";
                    $val['good_html'] .= "<div class='col-md-4'><div><a href='###' class='tooltip-show' data-toggle='tooltip' data-target='copy' title='' data-original-title='{$name}'>$s_name...</a></div><div>{$good['spec_name']}</div></div>";
                    $val['good_html'] .= "<div class='col-md-4'><div>{$good['total_price']}</div><div>{$good['good_num']}件</div></div>";
                    $val['good_html'] .= '</div>';
                }
                $val['good_html'] .= '</div>';
                unset($val['goods']);
                $val['user_html'] = $userInfo[$val['userid']]??'';
                $list[$key] = $val;
            }
            $return['data'] = $list;
            return $return;
        } else {
            $pay_status = DictCache::get('sys_order_pay_status');
            $order_status = DictCache::get('sys_order_order_status');
            Yii::$app->view->params['pay_status'] = $pay_status;
            Yii::$app->view->params['order_status'] = $order_status;
            Yii::$app->view->params['leftHtml'] = MenuService::getSubmenu();
            return parent::actionIndex();
        }
    }

    /**
     * 订单详情
     * @return string
     */
    public function actionDetail()
    {
        $id = Yii::$app->request->get('id', '');
        $data = Order::find()->where(['id' => $id])->with(['goods'])->asArray()->one();
        if (!$data) {
            return $this->bError('订单错误');
        }
        foreach ($data['goods'] as &$good) {
            $good['good_info_arr'] = json_decode($good['good_info'], true);
        }
        $user = User::find()->where(['id' => $data['userid']])->asArray()->one();
        $in = json_decode($user['info'],true);
        $user['nickname'] = $in['nickName']??'';
        $user['avatar'] = $in['avatarUrl']??'';
        $log = OrderLog::find()->where(['order_id' => $id])->orderBy(['create_time' => SORT_ASC])->asArray()->all();
        foreach ($data['goods'] as &$datum){
            $good_info = json_decode($datum['good_info'],true);
            $qr = '';
            $surplus_number = 0;
            if (in_array($data['order_status'],[1,2,3])!==false){//判断订单状态
                if (in_array($datum['refund_status'],[0,2])!==false){//判断订单商品状态
                    if ((int)$good_info['good_spec']['type'] ==2 && $datum['remain_time']>0){
                        $qrf = new QrCode($datum['id']);
                        $qr = $qrf->writeDataUri();
                        $surplus_number = $datum['remain_time'];
                    }
                }
            }
            $datum['qr'] = $qr;
            $datum['surplus_number'] = $surplus_number;
        }
        //获取订单评论
        $orderCommrnt = OrderComment::find()
            ->select(['logistics_star','service_attitude','content','create_time'])
            ->where(['order_id'=>$id])
            ->asArray()->all();
        $userid = array_column($orderCommrnt,'userid');
        $user11 = User::find()->select(['id','info'])->where(['id'=>$userid])->asArray()->all();
        $user11 = array_column($user11,'info','id');
        foreach ($orderCommrnt as &$value){
            $info = empty($user11[$value['userid']])?[]:json_decode($user11[$value['userid']],true);
            $value['nickname'] = $info['nickName']??'';
            $value['avatar'] = $info['avatarUrl']??'';
        }
        $order_status = DictCache::get('sys_order_order_status');
        $pay_status = DictCache::get('sys_order_pay_status');
        return $this->render('', [
            'data' => $data,
            'order_status' => $order_status,
            'pay_status' => $pay_status,
            'user' => $user,
            'log' => $log,
            'orderCommrnt' => $orderCommrnt,
        ]);
    }

    /**
     * 关闭订单
     * @return array
     */
    public function actionCancel()
    {
        $id = Yii::$app->request->post('id', '');
        $order = Order::find()->where(['id' => $id])->select(['order_status', 'id'])->one();
        if (!$order) {
            return commonApi::message('订单错误', false);
        }
        if ($order->order_status !== 0) {
            return commonApi::message('该订单不能关闭', false);
        }
        $order->order_status = 4;
        if ($order->save()) {
            //优惠券取消使用
            OrderLog::addLog(Yii::$app->user->id, $id, '商家订单关闭', '', 1);
            return commonApi::message('关闭成功');
        }
        return commonApi::message(commonApi::getModelError($order), false);
    }

    /**
     * 发货
     * @return array
     */
    public function actionDeliver()
    {
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            $id = $post['id'] ?? '';
            $model = Order::find()->where(['id' => $id])->select(['id', 'express_type', 'express_sn', 'order_status'])->one();
            if (!$model) {
                return commonApi::message('订单错误', false);
            }
            if ((int)$model['order_status'] !== 1) {
                return commonApi::message('该订单不能发货', false);
            }
            $model->express_type = $post['express_type'];
            $model->express_sn = $post['express_sn'];
            $model->order_status = 2;
            if ($model->save()) {
                OrderLog::addLog(Yii::$app->user->id, $id, '商家发货', '商家发货', 1);
                $receipt_time = System::getModel()->receipt_time;
                $receipt_time = $receipt_time??0;
                if ($receipt_time > 0) {
                    Yii::$app->queue->delay($receipt_time * 24 * 60 * 60)->push(new OrderBehavior([
                        'method' => OrderBehavior::ORDER_RECEIV,
                        'params' => ['id' => $id],
                    ]));
                }

                return commonApi::message('发货成功');
            }
            return commonApi::message(commonApi::getModelError($model), false);
        }
        $id = Yii::$app->request->get('id');
        $order = Order::find()->where(['id' => $id])
            ->with(['goods'])
            ->asArray()
            ->one();
        if (!$order) {
            return $this->bError('订单错误');
        }
        if ((int)$order['order_status'] !== 1) {
            return $this->bError('该订单不能发货');
        }
        foreach ($order['goods'] as &$good) {
            $good['good_info_arr'] = json_decode($good['good_info'], true);
        }
        $expressType = DictCache::get('sys_order_express_type');
        return $this->render('', ['data' => $order, 'expressType' => $expressType]);
    }

    /**
     * 售后
     * @return string
     */
    public function actionRefund()
    {
        $status = DictCache::get('sys_refund_status');
        if (Yii::$app->request->isPost) {
            $this->model = OrderRefund::className();
            $query = OrderRefund::find()
                ->alias('or')
                ->leftJoin(OrderGoods::tableName() . ' as og', 'og.id=or.order_good_id')
                ->leftJoin(Order::tableName() . ' as o', 'o.id=or.order_id')
                ->leftJoin(User::tableName() . ' as u', 'u.id=or.userid')
                ->select(['o.id', 'o.order_sn', 'o.pay_amount as order_amount',
                    'o.order_status', 'og.good_info',
                    'or.amount', 'or.create_time', 'or.create_time', 'or.id as or_id', 'or.status','or.userid'
                ]);
            $pageNum = 1;
            $pageSize = defined('PAGE_LIMIT') ? PAGE_LIMIT : 10;
            $param = \Yii::$app->request->post();
            $map = [];
            if (!empty($param['between']) && is_array($param['between'])) {
                foreach ($param['between'] as $paramField => $paramValue) {
                    if (is_array($paramValue) && count($paramValue) > 1) {
                        $start = $paramValue['start'];
                        $end = $paramValue['end'];
                        if ($start || $end) {
                            if ($start && $end) {
                                $map = ['between', $paramField, $start, $end];
                            } elseif ($start) {
                                $map = ['>', $paramField, $start];
                            } elseif ($end) {
                                $map = ['<', $paramField, $end];
                            }
                        }
                    }
                }
            }
            $query->andWhere($map);
            if (!empty($param['pageNum'])) $pageNum = intval($param['pageNum']);
            if (!empty($param['pageSize'])) $pageSize = intval($param['pageSize']);
            $offset = ($pageNum - 1) * $pageSize; //分页开始
            $list = $query->offset($offset)->limit($pageSize)->asArray()->all();
            $total = count($list);
            $order_status = DictCache::get('sys_order_order_status');
            $userid = array_unique(array_column($list,'userid'));
            $user = User::find()->where(['id'=>$userid])->select(['id','info'])->asArray()->all();
            $userInfo = (new User())->getUserHtml($user);
            foreach ($list as &$item) {
                $item['order_status'] = $order_status[$item['order_status']] ?? '';
                $item['status_title'] = $status[$item['status']] ?? '';
                $good_info = json_decode($item['good_info'], true);
                $good_img = $good_info['main_img'];
                $item['good_html'] = "<div id='good_{$item['id']}'><div><img style='width: 80px' src='{$good_img}' alt=''></div><div>{$good_info['name']}</div></div>";
                $item['user_html'] = $userInfo[$item['userid']]??'';
            }
            return commonApi::message('操作成功', true, $list, 0, '', ['total' => (int)$total]);
        }
        Yii::$app->view->params['leftHtml'] = MenuService::getSubmenu();
        return $this->render('', ['status' => $status]);
    }

    /**
     * 退款审核
     * @return bool|string
     */
    public function actionRefundReview()
    {
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if (empty($post['amount'])){
                return commonApi::message('请输入退款金额',false);
            }
            if (empty($post['status'])){
                return commonApi::message('请选择售后状态',false);
            }
            $info = OrderRefund::find()->where(['id' => $post['id']])->one();
            if ($post['status']==1){
                $sn = OrderRefund::makeOrderid();
                $result = OrderRefund::refund($info->order_id,$sn,$post['amount']);
                if (!$result['success']){
                    return commonApi::message($result['msg'],false);
                }
                $info->info = json_encode($result['data']);
                $msg = '审核成功，等待退款';
            }else{
                $msg = '审核成功';
            }
            $info->amount = $post['amount'];
            $info->status = $post['status'];
            $info->review_time = date('Y-m-d H:i:s');
            $info->review_remark = $post['review_remark']??'';
            $info->save();
            $statusAll = DictCache::get('sys_refund_status');
            OrderLog::addLog(Yii::$app->user->id,$info->order_id,"商家退款{$statusAll[$post['status']]}","商家退款{$statusAll[$post['status']]}：".$info->order_good_id,1);
            OrderGoods::updateAll(['refund_status'=>$post['status']+1],['id'=>$info->order_good_id]);
            return commonApi::message($msg);
        }
        $id = Yii::$app->request->get('id', '');
        $info = OrderRefund::find()->where(['id' => $id])->one();
        if (!$info) {
            return $this->bError('参数错误');
        }
        $status = DictCache::get('sys_refund_status');
        unset($status[0]);
        return $this->render('', ['info' => $info, 'status' => $status]);
    }

    /**
     * 修改价格
     * @return array|bool|string
     */
    public function actionEditAmount()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $pay_amount = 0;
            $updateId = [];
            $update = [];
            foreach ($post['spec'] as $value){
                $value['total_pay_price'] = empty($value['total_pay_price'])?0:$value['total_pay_price'];
                if ($value['total_pay_price']<0){
                    return commonApi::message('支付金额必须大于等于0',false);
                }
                $updateId[] = $value['id'];
                $update[] = ['total_pay_price'=>$value['total_pay_price']];
                $pay_amount += $value['total_pay_price'];
            }
            if ($updateId){
                $sql = TransformApi::batchUpdate(OrderGoods::getTableSchema()->name,$update,$updateId);
                Yii::$app->db->createCommand($sql)->execute();
            }
            $model = Order::find()->where(['id'=>$post['id']])->one();
            $old = $model->pay_amount;
            $model->pay_amount = $pay_amount;
            if ($model->save()!==false){
                if ($old-$model->pay_amount!==(float)0){
                    OrderLog::addLog(Yii::$app->user->id,$model->id,"修改付款金额","修改付款金额：修改前（{$old}），修改后（{$model->pay_amount}）");
                }
                return commonApi::message('修改成功');
            }
            return commonApi::message('修改失败',false);
        }
        $id = Yii::$app->request->get('id','');
        $model = Order::find()->where(['id'=>$id])->one();
        if ($model->pay_status!==0){
            return $this->bError('该订单不能修改价格');
        }
        $ordergoods = OrderGoods::find()
            ->where(['order_id'=>$id])
            ->select(['id','good_info','spec_name','good_name','good_num','total_pay_price'])
            ->asArray()->all();
        foreach ($ordergoods as &$good){
            $good_info = json_decode($good['good_info'],true);
            $good['main_img'] = $good_info['main_img'];
        }
        return $this->render('',['info'=>$model,'ordergoods'=>$ordergoods]);
    }

    public function actionComment()
    {
        $this->model = OrderComment::className();
        if (Yii::$app->request->isPost){
            $return = parent::actionIndex(true, [], ['status'=>'asc','create_time' => 'desc'], ['goods','order']);
            $arr = $return['data'];
            $user = new User();
            $userid = array_unique(array_column($arr,'userid'));
            $user = User::find()->where(['id'=>$userid])->select(['id','info'])->asArray()->all();
            $userInfo = (new User())->getUserHtml($user);
            foreach ($arr as &$value){
                $value['user_html'] = $userInfo[$value['userid']]??'';
                $value['goods_html'] = '';
                $value['order_html'] = '';
                if ($value['goods']){
                    $value['goods_html'] .= "<div id='good_{$value['id']}' style='text-align: center;'>";
                    $value['goods_html'] .= "<div><img style='width: 56px;' src='{$value['goods']['main_img']}' alt=''></div>";
                    $value['goods_html'] .= "<div>{$value['goods']['name']}</div>";
                    $value['goods_html'] .= "</div>";
                }
                if ($value['order']){
                    $value['order_html'] .= "<div><div>订单号：{$value['order']['order_sn']}</div><div>订单商品id：{$value['order_good_id']}</div></div>";
                }
            }
            $return['data'] = $arr;
            return $return;
        }
        $status = DictCache::get('sys_refund_status');
        Yii::$app->view->params['leftHtml'] = MenuService::getSubmenu();
        Yii::$app->view->params['statusAll'] = $status;
        return parent::actionIndex();
    }

    /**
     * 退款审核
     * @return bool|string
     */
    public function actionCommentReview()
    {
        if (Yii::$app->request->isPost) {
            $post = Yii::$app->request->post();
            if (empty($post['status'])){
                return commonApi::message('请选择售后状态',false);
            }
            $info = OrderComment::find()->where(['id' => $post['id']])->one();
            $info->status = $post['status'];
            $info->review_time = date('Y-m-d H:i:s');
            $info->review_remark = $post['review_remark']??'';
            $info->save();
            return commonApi::message('操作成功');
        }
        $id = Yii::$app->request->get('id', '');
        $info = OrderComment::find()->where(['id' => $id])->one();
        if (!$info) {
            return $this->bError('参数错误');
        }
        $status = DictCache::get('sys_refund_status');
        unset($status[0]);
        return $this->render('', ['info' => $info, 'status' => $status]);
    }
}